<template>
  <!-- 门诊医生-中医处方-药品列表 -->
  <div class="mb-2" :class="{ 'pointer-events-none': disabled }">
    <div class="flex justify-between items-center p-2 mt-4 order-header">
      <a-space>
        <div class="font-bold w-20">中药处方{{ orderIndex + 1 }}</div>
        <a-select v-model:value="orderData.zylb" class="w-20" @change="onChangeMedicineType">
          <a-select-option value="饮片">饮片</a-select-option>
          <a-select-option value="颗粒">颗粒</a-select-option>
        </a-select>
        <!-- 药房 -->
        <SelectDrugRoom v-model:value="orderData.drugStoreId" :params="{ storetype: 2 }" select-first class="w-52" @select="onSelectDrugRoom" />
        <a-select v-if="orderData.zylb === '饮片'" v-model:value="orderData.jzfs" class="w-20" :disabled="orderData.creamFormula === '1'">
          <a-select-option key="0" value="自煎">自煎</a-select-option>
          <a-select-option key="1" value="代煎">代煎</a-select-option>
        </a-select>
        <div class="flex-center ml-2">
          <span class="mr-1">膏方</span>
          <a-switch v-model:checked="orderData.creamFormula" un-checked-value="0" checked-value="1" @change="onGfChange" />
        </div>
      </a-space>
      <a-space>
        <!-- <a-button v-if="orderIndex === 0" type="primary" ghost @click="emit('add-order')">新增处方</a-button> -->
        <!-- <a-button type="primary" @click="onSign">签署</a-button> -->
        <a-button type="primary" ghost @click="saveAsTempOpen = true">另存为协定方</a-button>
        <SaveAsTemp v-model:open="saveAsTempOpen" :order-data="{ children: medicineList.filter((item) => item.mc) }" />
        <a-button type="primary" ghost @click="onOpenTemp">协定方</a-button>
        <a-button class="pointer-events-auto" @click="onPrint">打印处方</a-button>
        <div class="absolute top-[-9999px] hidden">
          <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
          <PrintView id="printMe" :print-data="printData" />
        </div>
        <BaseButton confirm-text="确认删除?" :icon="h(DeleteOutlined)" ghost danger size="small" @click="emit('delete-order', orderData.cfdh)" />
      </a-space>
    </div>
    <div class="mt-2 border">
      <!-- 中医药品列表 -->
      <div class="flex flex-wrap min-h-[80px]">
        <TCMItem
          v-for="item in medicineList"
          :key="item.key"
          :medicine-item="item"
          :medicine-list="medicineList"
          :is-last="medicineList.length === 1"
          :focus-key="focusKey"
          :tcm-type="orderData.zylb"
          @add-item="onAddItem"
          @change-item="isItemChanged = true"
          @delete-item="onDeleteItem"
          @focus-next="onFocusNext"
        />
      </div>
      <div class="order-footer">
        <div class="flex flex-1">
          <a-input
            v-model:value="orderData.fssl"
            v-input-selection
            class="input-style w-20"
            :disabled="orderData.creamFormula === '1'"
            :bordered="false"
            placeholder="数量"
            suffix="付"
          />
          <SelectTags v-model:value="orderData.yf" type="中药用法" class="ml-4 w-48 border-b-style" :bordered="false" tag-class="w-24" placeholder="用法" />
          <SelectTags v-model:value="orderData.pl" type="中药频率" class="ml-4 w-24 border-b-style" :bordered="false" tag-class="w-24" placeholder="频率" />
          <SelectTags v-model:value="orderData.jcl" type="煎出量" class="ml-4 w-24 border-b-style" :bordered="false" tag-class="w-24" placeholder="煎出量" />
          <a-input v-model:value="orderData.cmemo" :bordered="false" class="mx-4 flex-1 border-b-style" placeholder="备注" />
        </div>
        <div class="flex">
          <div class="mr-10 text-grey">{{ orderTotal?.cydfsl || 0 }}味 ，单付 {{ orderTotal?.df || 0 }}g，总计{{ orderTotal?.zj || 0 }}g</div>
          <div>￥{{ orderTotal?.zjjg || 0 }} 元</div>
        </div>
      </div>
      <!-- 加工 -->
      <div v-if="orderData.jzfs === '代煎'" class="order-footer">
        <div class="flex flex-1 overflow-hidden mr-2">
          <div class="font-bold mx-2">加工</div>
          <div class="flex-1 cursor-pointer border-b-style min-w-80" @click="orderData.creamFormula !== '1' && (processOpen = true)">
            <!-- <div v-if="orderData.processMethod.processMethodName" class="truncate" :title="generateProcess(orderData.processMethod)">
              {{ generateProcess(orderData.processMethod) }}
            </div>
            <span v-else class="color-placeholder"> 请输入快递信息 </span> -->
            <a-input :value="generateProcess(orderData.processMethod)" readonly :bordered="false" class="w-full pt-0" placeholder="请输入加工方式" />
          </div>
          <a-button type="text" danger size="small" :disabled="disabled" @click="onDelProcess()">删除</a-button>
        </div>
        <div class="text-right w-20">￥{{ formatAmount(orderData?.processMethod?.processMethodCost) }} 元</div>
      </div>
      <!-- 快递 -->
      <div class="order-footer pointer-events-auto">
        <div class="flex flex-1 overflow-hidden mr-2">
          <div class="font-bold mx-2">快递</div>
          <div class="flex-1 cursor-pointer border-b-style min-w-80" @click="onClickexpressOpen()">
            <!-- <div v-if="orderData.express.expressMode" class="truncate" :title="generateExpress(orderData.express)">
              {{ generateExpress(orderData.express) }}
            </div>
            <span v-else class="color-placeholder"> 请输入快递信息 </span> -->
            <a-input :value="generateExpress(orderData.express)" readonly :bordered="false" class="w-full pt-0" placeholder="请输入快递信息" />
          </div>
          <a-button v-if="orderData.express?.expressMode" type="text" danger size="small" @click="onDelExpress()">删除</a-button>
        </div>
        <div v-if="orderIndex > 0" class="mr-2">
          默认处方1地址 <a-switch v-model:checked="orderData.express.isUseOneAddress" :un-checked-value="0" :checked-value="1" @change="onUseOneAddress" />
        </div>
        <div class="text-right w-20">￥{{ formatAmount(orderData?.express?.expressCost) }} 元</div>
      </div>
      <div class="flex justify-between p-2 border-t border-dashed pr-8 items-center">
        <div class="w-40"></div>
        <a-button type="primary" class="pointer-events-auto" @click="onSaveMedicineList()">保存</a-button>
        <div class="w-40 text-right">
          <template v-if="orderData.jzfs === '代煎'">煎药费：{{ formatAmount(orderData.djCost) }}元</template>
        </div>
      </div>
    </div>
    <!-- 快递 -->
    <ModalExpress v-model:open="expressOpen" :row-data="orderData.express" :br-id="store.currentPatient.brId" @ok="onExpressOk" />
    <!-- 加工方式 -->
    <ModalProcess v-model:open="processOpen" :row-data="orderData.processMethod" @ok="onProcessOk" />
    <!-- 模板套餐 -->
    <TemplateModal v-model:open="tempModalOpen" @ok="onTempOk" />
  </div>
</template>
<script setup>
import { ref, toRaw, h, onMounted, createVNode, watch } from 'vue'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import BaseButton from '@/components/BaseButton'
import ModalExpress from '@/components/ModalExpress'
import ModalProcess from '@/components/ModalProcess'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import { getSystemConfig } from '@/utils/systemConfig'
import useStore from '../../store'
import TemplateModal from './TemplateModal'
import SaveAsTemp from './SaveAsTemp'
import PrintView from './PrintView'
import TCMItem from './TCMItem'

const { empId } = useUserStore()
const store = useStore()
const emit = defineEmits(['delete-order', 'refresh'])
const props = defineProps({
  orderIndex: {
    type: Number,
    default: 0
  },
  orderItem: {
    type: Object,
    default: () => ({})
  },
  jzbh: {
    type: String,
    default: ''
  },
  oneOrderAddress: {
    type: Object,
    default: () => ({})
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
const orderData = ref({
  jzfs: getSystemConfig('OUTP_DOCTOR_TCM_DEFAULT_BOIL_MODE') === '1' ? '代煎' : '自煎',
  zylb: '饮片',
  fssl: getSystemConfig('ZYCFFS_DEFAULT'), //中药处方付数
  yf: getSystemConfig('ZYCFJF_DEFAULT'), //中药处方用法
  pl: getSystemConfig('ZYCFPL_DEFAULT'), //中药处方频率
  jcl: getSystemConfig('ZYCFJCL_DEFAULT'), //中药处方煎出量
  ...props.orderItem
})
const orderTotal = ref({})
const saveAsTempOpen = ref(false)
const tempModalOpen = ref(false)
const isItemChanged = ref(false)
const focusKey = ref(null)
const medicineList = ref([])

const processOpen = ref(false)
const expressOpen = ref(false)
const generateProcess = (processMethod = {}) => {
  if (!processMethod.processMethodName) return ''
  return `${processMethod.processMethodName} ${processMethod.processMethodCmemo || ''}`
}
const generateExpress = (express = {}) => {
  if (!express.expressMode) return ''
  return `【${express.expressMode || ''}】${express.contactName || ''}，${express.contactPhone || ''}，${express.provinceName || ''}${express.cityName || ''}${
    express.countyName || ''
  }${express.addressDetail || ''} ${express.expressCmemo || ''}`
}
//获取合计信息
const getTotal = async () => {
  const res = await post('/outp/outpClinicalOrder/getOutpTCMTotalInfo', { cfdh: orderData.value.cfdh, fs: orderData.value.fssl })
  if (res.code !== 0) return message.error(res.msg)
  orderTotal.value = res.data
}

//获取药品列表
const getMedicineList = async () => {
  const res = await post('/outp/outpClinicalOrder/getOutpTCMDetailList', { cfdh: orderData.value.cfdh })
  if (res.code !== 0) return message.error(res.msg)
  if (res.data.length > 0) {
    medicineList.value = res.data
    !props.disabled && medicineList.value.push({ key: res.data.length })
    getTotal()
  } else {
    medicineList.value = [{ key: 0 }]
  }
}

//获取快递信息
const onClickexpressOpen = async () => {
  if (orderData.value.express.isUseOneAddress) return message.warning('默认处方1地址无法修改')
  expressOpen.value = true
}

const onAddItem = (key) => {
  const isLast = medicineList.value.at(-1)?.key === key
  isLast && medicineList.value.push({ key: medicineList.value.length })
}
const onFocusNext = (key) => {
  focusKey.value = key
}
const onSaveMedicineList = async () => {
  // if (!(await onEditOrder())) return
  const list = toRaw(medicineList.value)
  const params = list
    .filter((item) => !!item.mc)
    .map((item) => {
      return {
        ...item,
        ysbh: empId,
        cfdh: orderData.value.cfdh
      }
    })
  orderData.value.children = params
  const params1 = {
    keycode: props.jzbh,
    ...orderData.value
  }
  const { code, msg } = await post('/outp/outpClinicalOrder/doSaveOutpTCMHead', params1)
  if (code !== 0) return message.error(msg || '操作失败')
  getTotal()
  const res = await post('/outp/outpClinicalOrder/doSaveOutpTCMDetail', params)
  if (res.code !== 0) return message.error(res.msg || '保存失败')
  message.destroy()
  message.success('保存成功')
  // await post('/outp/mzys/signedDoctor', {
  //   yzid: ['21021', '21022', '21023', '21027'],
  //   yzzt: 1
  // })
  isItemChanged.value = false
  emit('refresh')
  getMedicineList()
}

const onDeleteItem = async (row) => {
  if (row.lsh) {
    const res = await post('/outp/outpClinicalOrder/doDeleteOutpTCMDetail', { cfmxdh: row.lsh })
    if (res.code !== 0) return message.error(res.msg)
    message.destroy()
    message.success('删除成功')
    getMedicineList()
  } else {
    medicineList.value.splice(medicineList.value.indexOf(row), 1)
  }
}

const onOpenTemp = () => {
  tempModalOpen.value = true
}
const onTempOk = (select) => {
  if (!select.length) return
  const newData = []
  const existData = []
  select.forEach((item) => {
    const isExist = medicineList.value.some((v) => v.mc === item.mc)
    if (!isExist) {
      newData.push({ ...item, key: `temp-${Math.random().toString().slice(2)}`, isNew: true, source: 'temp' })
    } else {
      existData.push(item.mc)
    }
  })
  existData.length && message.error(`【${existData.join('，')}】已存在，未添加`)
  medicineList.value = [...medicineList.value, ...newData].filter((item) => item.mc)
  medicineList.value.push({ key: select.length })
  isItemChanged.value = true
}
//保存快递
const onExpressOk = (res) => {
  orderData.value.express = res
  onSaveMedicineList()
}
//保存加工方式
const onProcessOk = (res) => {
  orderData.value.processMethod = res
  onSaveMedicineList()
}
const onDelExpress = () => {
  orderData.value.express = {}
  onSaveMedicineList()
}
const onDelProcess = () => {
  orderData.value.processMethod = {}
  onSaveMedicineList()
}
const onChangeMedicineType = (type) => {
  //type 0:饮片 1颗粒
  if (!medicineList.value[0].mc) return
  Modal.confirm({
    title: '确定切换药品类型吗？',
    icon: createVNode(ExclamationCircleOutlined),
    centered: true,
    maskClosable: true,
    width: 560,
    content: createVNode(
      'div',
      { style: 'margin:24px 0;font-size:15px' },
      type === 0 ? '若更换为饮片，将自动清空颗粒药品' : '若更换为颗粒，将自动清空饮片药品'
    ),
    onOk() {
      orderData.value.jzfs = getSystemConfig('OUTP_DOCTOR_TCM_DEFAULT_BOIL_MODE') === '1' ? '代煎' : '自煎'
      orderTotal.value = {}
      medicineList.value = [{ key: 0 }]
    },
    onCancel() {
      orderData.value.zylb = orderData.value.zylb === '饮片' ? '颗粒' : '饮片'
    }
  })
}
const printMe = ref(null)
const printData = ref({})
const onSelectDrugRoom = (options) => {
  orderData.value.drugStoreName = options.storeName
}
const onPrint = async () => {
  // window.open(`/api/v1/outp/outPrint/printTraditionalChineseMedicinePrescriptionRaft?cfdh=${orderData.value.cfdh}`)
  const { code, msg, data } = await post('/outp/outPrint/getTraditionalChineseMedicinePrescriptionRaft', { cfdh: orderData.value.cfdh })
  if (code !== 0) return message.error(msg)

  const isArmy = getSystemConfig('NAVYHIS_MODE') === '1'
  if (isArmy) {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
const onUseOneAddress = (checked) => {
  if (checked) {
    orderData.value.express = props.oneOrderAddress
    orderData.value.express.isUseOneAddress = 1
  } else {
    orderData.value.express.id = ''
    orderData.value.express.patientAddressId = ''
    orderData.value.express.isUseOneAddress = 0
  }
}
const onGfChange = async (val) => {
  if (val === '1') {
    orderData.value.jzfs = '代煎'
    orderData.value.fssl = '1'
    const { code, data, msg } = await post('/operation/opex/getCreamFormulaProcessMethodInfo')
    if (code !== 0) return message.error(msg || '获取膏方加工方式失败')
    orderData.value.processMethod = data
    orderData.value.processMethod.processMethodCost = data.dj || 0
  }
}
watch(
  () => orderData.value.express.isUseOneAddress,
  (val) => {
    if (val) {
      orderData.value.express = { ...props.oneOrderAddress, expressCost: 0 }
      orderData.value.express.isUseOneAddress = 1
      orderData.value.express.patientAddressId = props.oneOrderAddress.id
      orderData.value.express.kdaddr = props.oneOrderAddress.addressDetail
    } else {
      orderData.value.express.expressCost = props.oneOrderAddress.expressCost
      orderData.value.express.isUseOneAddress = 0
      orderData.value.express.patientAddressId = ''
      orderData.value.express.kdaddr = ''
    }
  }
)

onMounted(() => {
  getMedicineList()
})
</script>
<style lang="less" scoped>
.order-footer {
  @apply border-t border-dashed flex justify-between items-center py-2 pr-8;
}
.order-header {
  background-color: var(--thin-color);
  border-radius: 2px;
  &:first-child {
    margin-top: 0;
    border: none;
  }
}

:deep(.border-b-style) {
  border-bottom: 1px solid var(--border-color) !important;
  // border-bottom: 1px solid transparent;
  border-radius: 0;
  cursor: pointer;
  &:hover {
    border-bottom: 1px solid var(--primary-color) !important;
  }
}
.input-style {
  padding: 0 12px;
  :deep(.ant-input) {
    padding-right: 4px;
    text-align: center !important;
    border-bottom: 1px solid var(--border-color) !important;
    cursor: pointer;
    &:hover {
      border-bottom-color: var(--primary-color) !important;
    }
  }
}
.color-placeholder {
  color: var(--disabled-text-color);
}
</style>
